import { FormCard } from '@components/FormCard'
import { FormUpload } from '@components/FormUpload'
import { useFormCallback } from '@hooks/useFormCallback'
import {
  useNewsCategoryQuery,
  useNewsCreateMutation,
  useNewsDetailQuery,
  useNewsUpdateMutation,
} from '@services/news'
import { Link } from '@tanstack/react-router'
import { Breadcrumb, Button, DatePicker, Form, Input, InputNumber, Select, Switch } from 'antd'
import dayjs from 'dayjs'
import { useEffect, useState } from 'react'
import ImagePreview from './ImagePreview'

const defaultData = {
  image: '',
  links: [],
  orderby: 0,
  hide: false,
  published_at: dayjs(),
}

export function FormNews({ id }) {
  console.log('%c Line:9 🍒 id', 'color:#b03734', id)
  const [form] = Form.useForm()
  const [loading, setLoading] = useState(true)

  const { isPending, data: categoryList } = useNewsCategoryQuery()

  const [data, setData] = useState({ ...defaultData })
  const { data: newsData } = useNewsDetailQuery(+id)
  const [attachments, setAttachments] = useState(defaultData.links)

  const { mutate } = id ? useNewsUpdateMutation() : useNewsCreateMutation()
  const { onFinish, onFailed } = useFormCallback(mutate, {
    handle: (data) => {
      return {
        ...data,
        ...(id && { id }),
        links: attachments,
        published_at: dayjs(data.published_at).format('YYYY-MM-DD HH:mm:ss'),
      }
    },
  })

  useEffect(() => {
    if (id >= 0) {
      // TODO: 获取新闻详情
      console.log('%c Line:40 🍆 newsData', 'color:#b03734', newsData)
      if (newsData) {
        setData(newsData)
        setAttachments(newsData.links || [])
        newsData.published_at = dayjs(newsData.published_at)
      }
      form.setFieldsValue({ ...defaultData, ...newsData })
      setLoading(false)
    }
  }, [id, newsData])

  if (loading) return null

  const card = {
    title: (
      <Breadcrumb
        items={[
          { title: '新闻中心' },
          { title: <Link to="..">新闻列表</Link> },
          { title: id ? '编辑' : '发布' },
        ]}
      />
    ),
  }

  return (
    <FormCard card={card}>
      <Form
        name="form-news"
        labelCol={{ span: 4 }}
        wrapperCol={{ span: 18 }}
        style={{ maxWidth: '100%' }}
        form={form}
        onFinish={onFinish}
        onFinishFailed={onFailed}
        autoComplete="off">
        <Form.Item
          label="新闻标题"
          name="title"
          rules={[{ required: true, message: '请输入标题' }]}>
          <Input />
        </Form.Item>
        <Form.Item
          label="新闻类型"
          name="type"
          rules={[{ required: true, message: '请输入标题' }]}>
          <Select
            loading={isPending}
            style={{ width: 360 }}
            placeholder="--- 请选择 ---"
            options={categoryList?.map(({ id: value, name: label }) => ({ value, label }))}
          />
        </Form.Item>
        <Form.Item
          label="新闻封面"
          name="image"
          rules={[{ required: true, message: '请上传新闻封面' }]}>
          <ImagePreview
            key="image"
            aspect="9:4"
            url={data.image}
            onChange={(resp) => {
              setData({ ...data, image: resp.url })
              form.setFieldValue('image', resp.url)
            }}
          />
        </Form.Item>

        <Form.Item
          label="新闻描述"
          name="description"
          rules={[{ required: true, message: '请输入新闻描述' }]}>
          <Input.TextArea rows={3} />
        </Form.Item>
        <Form.Item
          className="w-full"
          label="新闻内容"
          name="content"
          rules={[{ required: true, message: '请输入新闻内容' }]}>
          <Input.TextArea rows={5} />
        </Form.Item>

        <Form.Item label="附　　件" name="links" width={'206px'}>
          <FormUpload btnText="上传附件" filelist={attachments} onChange={setAttachments} />
        </Form.Item>

        <Form.Item label="排　　序" name="orderby" width={'206px'}>
          <InputNumber className="w-[206px]!" min={0} />
        </Form.Item>
        <Form.Item label="是否隐藏" name="hide">
          <Switch checkedChildren="隐藏" unCheckedChildren="显示" />
        </Form.Item>
        <Form.Item label="发布时间" name="published_at">
          <DatePicker className="w-[206px]!" />
        </Form.Item>
        <Form.Item label={null}>
          <Button type="primary" htmlType="submit">
            保 存
          </Button>
        </Form.Item>
      </Form>
    </FormCard>
  )
}
